package com.snowfield.lb47.lbconfig.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.snowfield.lb47.lbconfig.domain.Backserver;
import com.snowfield.lb47.lbconfig.domain.BackserverCrt;
import com.snowfield.lb47.lbconfig.mapper.BackserverCrtMapper;
import com.snowfield.lb47.lbconfig.mapper.BackserverMapper;
import com.snowfield.lb47.lbconfig.service.IBackserverService;
import com.snowfield.lb47.utils.BackserverCache;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后端服务器Service业务层处理
 *
 * @author snowfield
 * @date 2024-03-25
 */
@Service
public class BackserverServiceImpl implements IBackserverService {
    @Autowired
    private BackserverMapper backserverMapper;
    @Autowired
    private BackserverCrtMapper backserverCrtMapper;

    /**
     * 1.重新加载后端服务器数据到缓存中
     * 2.重新加载后端服务器概要信息到缓存中
     * <p>
     * 相当于每次tomcat生新启动后,都重新加载一次数据
     */
    @PostConstruct
    public void initCache() {
        List<Backserver> backserverList = selectBackserverList(new Backserver());

        /**
         * 1.重新加载后端服务器数据
         */
        BackserverCache.clearServerCache();
        List<Backserver> backserverList2 = new ArrayList<>();
        for (Backserver server : backserverList) {
            backserverList2.add(selectBackserverById(server.getId()));
        }
        BackserverCache.setServerCache(backserverList2);

        /**
         * 2.重新加载后端服务器概要信息
         */
        BackserverCache.removeServerSummaryCache();
        Map<String, Map<String, String>> backserverSummary = new HashMap<>();
        for (Backserver server : backserverList) {
            HashMap<String, String> serverHashMap = new HashMap<>();
            serverHashMap.put("serverName", server.getServerName());
            serverHashMap.put("serverIp", server.getServerIp());

            backserverSummary.put(String.valueOf(server.getId()), serverHashMap);
        }

        BackserverCache.setServerSummaryCache(backserverSummary);
    }

    /**
     * 查询后端服务器
     *
     * @param id 后端服务器主键
     * @return 后端服务器
     */
    @Override
    public Backserver selectBackserverById(Long id) {
        return backserverMapper.selectBackserverById(id);
    }

    /**
     * 查询后端服务器列表
     *
     * @param backserver 后端服务器
     * @return 后端服务器
     */
    @Override
    public List<Backserver> selectBackserverList(Backserver backserver) {
        return backserverMapper.selectBackserverList(backserver);
    }

    /**
     * 新增后端服务器
     *
     * @param backserver 后端服务器
     * @return 结果
     */
    @Override
    public int insertBackserver(Backserver backserver) {
        backserver.setCreateTime(DateUtils.getNowDate());
        Integer affectRows = backserverMapper.insertBackserver(backserver);
        if (affectRows > 0) {
            //更新后端服务器缓存数据
            BackserverCache.setServerCache(String.valueOf(backserver.getId()), backserver);
        }
        return affectRows;
    }

    /**
     * 修改后端服务器
     *
     * @param backserver 后端服务器
     * @return 结果
     */
    @Override
    public int updateBackserver(Backserver backserver) {
        backserver.setUpdateTime(DateUtils.getNowDate());
        Integer affectRows = backserverMapper.updateBackserver(backserver);
        if (affectRows > 0) {
            //更新后端服务器缓存数据
            BackserverCache.setServerCache(String.valueOf(backserver.getId()), backserver);
        }
        return affectRows;
    }

    /**
     * 批量删除后端服务器
     *
     * @param ids 需要删除的后端服务器主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBackserverByIds(Long[] ids) {
        List<BackserverCrt> backserverCrtList = backserverCrtMapper.selectBackserverCrtListByServerIds(ids);
        List<String> crtPathList = new ArrayList<>();
        for (BackserverCrt crt : backserverCrtList) {
            if (StringUtils.isNotEmpty(crt.getCrtPath())) {
                crtPathList.add(crt.getCrtPath());
            }
        }
        Integer delServerCnt = backserverMapper.deleteBackserverByIds(ids);
        if (delServerCnt > 0) {
            if (backserverCrtList.size() > 0) {
                Integer delCrtCnt = backserverCrtMapper.deleteBackserverCrtByServerIds(ids);
                if (delCrtCnt > 0) {
                    for (String crtPath : crtPathList) {
                        if (new File(crtPath).exists()) {
                            FileUtils.deleteQuietly(new File(crtPath));
                        }
                    }
                }
            }

            //更新后端服务器缓存数据
            for (Long id : ids) {
                BackserverCache.removeServerCache(String.valueOf(id));
            }
        }

        return delServerCnt;
    }

    /**
     * 删除后端服务器信息
     *
     * @param id 后端服务器主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBackserverById(Long id) {
        Long[] ids = new Long[]{id};
        List<BackserverCrt> backserverCrtList = backserverCrtMapper.selectBackserverCrtListByServerIds(ids);
        List<String> crtPathList = new ArrayList<>();
        for (BackserverCrt crt : backserverCrtList) {
            if (StringUtils.isNotEmpty(crt.getCrtPath())) {
                crtPathList.add(crt.getCrtPath());
            }
        }

        Integer delServerCnt = backserverMapper.deleteBackserverById(id);
        if (delServerCnt > 0) {
            if (backserverCrtList.size() > 0) {
                Integer delCrtCnt = backserverCrtMapper.deleteBackserverCrtByServerIds(ids);
                if (delCrtCnt > 0) {
                    for (String crtPath : crtPathList) {
                        if (new File(crtPath).exists()) {
                            FileUtils.deleteQuietly(new File(crtPath));
                        }
                    }
                }
            }

            //更新后端服务器缓存数据
            BackserverCache.removeServerCache(String.valueOf(id));
        }

        return delServerCnt;
    }

    /**
     * 校验后端服务器名称是否唯一
     *
     * @param backserver 后端服务器
     * @return 结果
     */
    @Override
    public Boolean checkNameUnique(Backserver backserver) {
        Long serverId = backserver.getId();
        Backserver server = backserverMapper.selectBackserverByName(backserver.getServerName());
        if (server != null && !server.getId().equals(serverId)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 校验后端服务器IP地址是否唯一
     *
     * @param backserver 后端服务器
     * @return 结果
     */
    public Boolean checkIpUnique(Backserver backserver) {
        Long serverId = backserver.getId();
        Backserver server = backserverMapper.selectBackserverByIp(backserver.getServerIp());
        if (server != null && !server.getId().equals(serverId)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 获取后端服务器IP地址与名称的对应关系
     *
     * @return 结果
     */
    public HashMap<String, String> selectServerIPNameMap() {
        List<Backserver> backserverList = this.selectBackserverList(new Backserver());
        HashMap<String, String> serverIPNameMap = new HashMap<>();
        for (Backserver backserver : backserverList) {
            serverIPNameMap.put(backserver.getServerIp(), backserver.getServerName());
        }

        return serverIPNameMap;
    }

    /**
     * 获取后端服务器概要信息
     *
     * @return 结果
     */
    public Map<String, Map<String, String>> selectServerSummary() {
        Map<String, Map<String, String>> serverSummary = BackserverCache.getServerSummaryCache();
        if (serverSummary == null || serverSummary.isEmpty()) {
            //缓存数据不存在，从数据库中获取并加入到缓存
            List<Backserver> backserverList = backserverMapper.selectBackserverList(new Backserver());
            Map<String, Map<String, String>> backserverSummary = new HashMap<>();
            for (Backserver item : backserverList) {
                HashMap<String, String> itemHashMap = new HashMap<>();
                itemHashMap.put("serverName", item.getServerName());
                itemHashMap.put("serverIp", item.getServerIp());

                backserverSummary.put(String.valueOf(item.getId()), itemHashMap);
            }

            BackserverCache.setServerSummaryCache(backserverSummary);

            return backserverSummary;
        }
        //缓存中存在
        return serverSummary;
    }
}
